package com.zzh.partnersys.ai.controller;

import com.zzh.partnersys.ai.entity.AiAssistantDO;
import com.zzh.partnersys.ai.entity.request.AiAssistantCreateRequest;
import com.zzh.partnersys.ai.entity.request.AiAssistantStatusRequest;
import com.zzh.partnersys.ai.entity.request.AiAssistantUpdateRequest;
import com.zzh.partnersys.ai.entity.response.AiAssistantVO;
import com.zzh.partnersys.ai.service.AiAssistantService;
import com.zzh.partnersys.common.exception.ResultCodeEnum;
import com.zzh.partnersys.common.exception.ResultUtils;
import com.zzh.partnersys.common.util.SessionUtils;
import com.zzh.partnersys.common.util.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * AI助手控制器
 *
 * @author zzh
 * @since 2025-01-XX
 */
@Slf4j
@RestController
@RequestMapping("/assistant")
public class AiAssistantController {

    @Resource
    private AiAssistantService aiAssistantService;

    /**
     * 创建AI助手
     *
     * @param request 创建请求
     * @param httpRequest Http请求
     * @return 创建的助手对象
     */
    @PostMapping("/create")
    public ResultUtils<AiAssistantDO> createAssistant(@RequestBody AiAssistantCreateRequest request,
                                                       HttpServletRequest httpRequest) {
        // 参数校验
        if (request == null || request.getAssistantName() == null || request.getAssistantName().trim().isEmpty()) {
            return ResultUtils.build(null, ResultCodeEnum.PARAMS_ERROR);
        }

        // 获取当前用户ID
        Long userId = TokenUtils.getCurrentUserIdOrThrow(httpRequest);

        // 创建助手
        AiAssistantDO assistant = aiAssistantService.createAssistant(
                userId,
                request.getAssistantName(),
                request.getRoleDesc(),
                request.getGreeting(),
                request.getDocList()
        );
        return ResultUtils.ok(assistant);
    }

    /**
     * 更新AI助手信息
     *
     * @param request 更新请求
     * @param httpRequest Http请求
     * @return 更新后的助手对象
     */
    @PostMapping("/update")
    public ResultUtils<AiAssistantDO> updateAssistant(@RequestBody AiAssistantUpdateRequest request,
                                                       HttpServletRequest httpRequest) {
        // 参数校验
        if (request == null || request.getAssistantId() == null || request.getAssistantId() <= 0) {
            return ResultUtils.build(null, ResultCodeEnum.PARAMS_ERROR);
        }

        // 获取当前用户ID
        Long userId = SessionUtils.getCurrentUserIdOrThrow(httpRequest);

        // 更新助手
        AiAssistantDO assistant = aiAssistantService.updateAssistant(
                request.getAssistantId(),
                userId,
                request.getAssistantName(),
                request.getRoleDesc(),
                request.getGreeting()
        );

        return ResultUtils.ok(assistant);
    }

    /**
     * 删除AI助手（逻辑删除）
     *
     * @param assistantId 助手ID
     * @param httpRequest Http请求
     * @return 是否删除成功
     */
    @DeleteMapping("/delete/{assistantId}")
    public ResultUtils<Boolean> deleteAssistant(@PathVariable Long assistantId,
                                                 HttpServletRequest httpRequest) {
        // 参数校验
        if (assistantId == null || assistantId <= 0) {
            return ResultUtils.build(null, ResultCodeEnum.PARAMS_ERROR);
        }

        // 获取当前用户ID
        Long userId = SessionUtils.getCurrentUserIdOrThrow(httpRequest);

        // 删除助手
        boolean deleted = aiAssistantService.deleteAssistant(assistantId, userId);

        return ResultUtils.ok(deleted);
    }

    /**
     * 设置默认助手
     *
     * @param assistantId 助手ID
     * @param httpRequest Http请求
     * @return 是否设置成功
     */
    @PostMapping("/set-default/{assistantId}")
    public ResultUtils<Boolean> setDefaultAssistant(@PathVariable Long assistantId,
                                                     HttpServletRequest httpRequest) {
        // 参数校验
        if (assistantId == null || assistantId <= 0) {
            return ResultUtils.build(null, ResultCodeEnum.PARAMS_ERROR);
        }

        // 获取当前用户ID
        Long userId = SessionUtils.getCurrentUserIdOrThrow(httpRequest);

        // 设置默认助手
        boolean success = aiAssistantService.setDefaultAssistant(assistantId, userId);

        return ResultUtils.ok(success);
    }

    /**
     * 获取用户的默认助手
     *
     * @param httpRequest Http请求
     * @return 默认助手对象
     */
    @GetMapping("/default")
    public ResultUtils<AiAssistantDO> getDefaultAssistant(HttpServletRequest httpRequest) {
        // 获取当前用户ID
        Long userId = SessionUtils.getCurrentUserIdOrThrow(httpRequest);

        // 获取默认助手
        AiAssistantDO assistant = aiAssistantService.getDefaultAssistant(userId);

        return ResultUtils.ok(assistant);
    }

    /**
     * 获取用户的所有助手列表
     *
     * @param httpRequest Http请求
     * @return 助手列表（包含文档信息）
     */
    @GetMapping("/list")
    public ResultUtils<List<AiAssistantVO>> getUserAssistants(HttpServletRequest httpRequest) {
        // 获取当前用户ID
        Long userId = TokenUtils.getCurrentUserIdOrThrow(httpRequest);

        // 获取助手列表（包含文档信息）
        List<AiAssistantVO> assistants = aiAssistantService.getUserAssistants(userId);

        return ResultUtils.ok(assistants);
    }

    /**
     * 根据ID获取助手详情
     *
     * @param assistantId 助手ID
     * @return 助手对象
     */
    @GetMapping("/detail/{assistantId}")
    public ResultUtils<AiAssistantDO> getAssistantById(@PathVariable Long assistantId) {
        // 参数校验
        if (assistantId == null || assistantId <= 0) {
            return ResultUtils.build(null, ResultCodeEnum.PARAMS_ERROR);
        }

        // 获取助手
        AiAssistantDO assistant = aiAssistantService.getAssistantById(assistantId);

        return ResultUtils.ok(assistant);
    }

    /**
     * 启用/禁用助手
     *
     * @param request 状态更新请求
     * @param httpRequest Http请求
     * @return 是否更新成功
     */
    @PostMapping("/update-status")
    public ResultUtils<Boolean> updateAssistantStatus(@RequestBody AiAssistantStatusRequest request,
                                                       HttpServletRequest httpRequest) {
        // 参数校验
        if (request == null || request.getAssistantId() == null || request.getAssistantId() <= 0) {
            return ResultUtils.build(null, ResultCodeEnum.PARAMS_ERROR);
        }
        if (request.getStatus() == null || (request.getStatus() != 0 && request.getStatus() != 1)) {
            return ResultUtils.build(null, ResultCodeEnum.PARAMS_ERROR);
        }

        // 获取当前用户ID
        Long userId = SessionUtils.getCurrentUserIdOrThrow(httpRequest);

        // 更新状态
        boolean success = aiAssistantService.updateAssistantStatus(
                request.getAssistantId(),
                userId,
                request.getStatus()
        );

        return ResultUtils.ok(success);
    }
}

